(function () {
  var stateMap, elemMap, setElemMap, bindElemEvent, splitChannel, handleChangeRange,
    handleClickTrim, calcRepayment, fetchBanner, renderBanner, adjustBannerHeight,
    handleClickApply;

  stateMap = {
    multiple: 2000,
    rate    : 0.09/12,
    money   : 0,
    trim    : 3
  };

  //解析url中是否存在渠道的信息
  splitChannel = function () {
    var url = util.splitUrl(location.search);
    if (url.channel) {
      localStorage.jqyChannel = url.channel;
    } else {
      localStorage.jqyChannel = 'H5';
    }
  };

  //计算每月还款金额
  calcRepayment = function () {
    var mm = stateMap.money * stateMap.rate * Math.pow(1 + stateMap.rate, stateMap.trim)
      / (Math.pow((1 + stateMap.rate), stateMap.trim) - 1);
    elemMap.infoMonth.innerHTML = mm.toFixed(2);
  };

  //拖动了input的范围
  handleChangeRange = function () {
    //设置选择的范围样式
    elemMap.moneyRange.style.backgroundSize = this.value + '% 100%';
    stateMap.money = this.value * stateMap.multiple;
    elemMap.applyMoney.innerHTML = util.splitMoney(stateMap.money.toFixed(2).toString());

    //计算
    calcRepayment();
  };

  //选择了贷款期限
  handleClickTrim = function () {
    util.nList2Arr(elemMap.trimWrap.querySelectorAll('div')).forEach(function (trim) {
      trim.classList.remove('active');
    });
    this.classList.add('active');
    stateMap.trim = parseInt(this.innerHTML);
    elemMap.infoTrim.innerHTML = stateMap.trim;

    //计算
    calcRepayment();
  };

  //点击了立即申请
  handleClickApply = function () {
    /*************S 记录点击信息************/
    var temp = JSON.parse(localStorage.TJBasic);
    temp.CurrentPage = '首页';
    temp.time = (new Date()).valueOf();
    temp.behavior = '点击立即申请';
    temp.money = stateMap.money;
    temp.term = stateMap.trim+'天';
    temp.sfLogin = localStorage.jqyPhone ? '是' : '否';
    temp.loginType = '密码登录';
    var arr = JSON.parse(localStorage.TJArray);
    arr.push(temp);
    localStorage.TJArray = JSON.stringify(arr);
    /*************E 记录点击信息************/

    //如果没有登录，则先登录
    if (!localStorage.jqyPhone) {
      util.toast('请先登录！');
      setTimeout(function () {
        location.href = './signIn.html';
      }, 2600);
    } else {
      location.href = './proList.html?m='+stateMap.money+'&t='+stateMap.trim;
    }
  };

  //设置banner的高度
  adjustBannerHeight = function () {
    var hgt = window.innerHeight
      - elemMap.loanInfoWrap.getBoundingClientRect().bottom
      - elemMap.footNav.clientHeight;

    elemMap.bannerWrap.style.height = hgt + 'px';
  };

  //获取banner数据
  fetchBanner = function () {
    $.ajax({
      url: util.hostUrl + '/v1/banner/banner.html',
      type: 'post',
      data: {
        header: JSON.stringify({
          reqKey: util.reqKey
        }),
        param: JSON.stringify({
          app: util.app
        })
      },
      success: function (res) {
        console.log(res);
        if (res.result.code == 1) {
          renderBanner(res.response.banner);
        }
      }
    })
  };

  //渲染banner数据
  renderBanner = function (list) {
    var lists = list.map(function (val) {
      var url = val.type == 1 ? './proDetail.html?id=' + val.inId : val.url;
      return '<div class="swiper-slide" style="background-image: url('+
        val.logo +')"><a href="'+ url +'"></div>';
    });
    elemMap.bannerWrap.querySelector('.swiper-wrapper').innerHTML
      = lists.join('');

    util.nList2Arr(elemMap.bannerWrap.querySelectorAll('a')).forEach(function (a) {
      a.addEventListener('click', function (e) {
        e.preventDefault();
        /*************S 记录点击信息************/
        var temp = JSON.parse(localStorage.TJBasic);
        temp.CurrentPage = '首页';
        temp.time = (new Date()).valueOf();
        temp.behavior = '点击banner';
        temp.sfLogin = localStorage.jqyPhone ? '是' : '否';
        temp.loginType = '密码登录';
        var arr = JSON.parse(localStorage.TJArray);
        arr.push(temp);
        localStorage.TJArray = JSON.stringify(arr);
        /*************E 记录点击信息************/
        location.href = this.getAttribute('href');
      })
    });

    Swiper(elemMap.bannerWrap, {
      loop: true,
      autoplay: 5000,
      autoplayDisableOnInteraction : false
    })
  };

  bindElemEvent = function () {
    elemMap.moneyRange.addEventListener('input', handleChangeRange);
    util.nList2Arr(elemMap.trimWrap.querySelectorAll('div')).forEach(function (trim) {
      trim.addEventListener('click', handleClickTrim);
    });
    elemMap.applyNow.addEventListener('click', handleClickApply);
  };

  setElemMap = function () {
    elemMap = {
      applyMoney    : document.querySelector('.apply-money'),
      infoMonth     : document.querySelector('.info-month'),
      infoTrim      : document.querySelector('.info-trim'),
      trimWrap      : document.querySelector('.trim-wrap'),
      moneyRange    : document.querySelector('.money-range'),
      loanInfoWrap  : document.querySelector('.loan-info-wrap'),
      applyNow      : document.querySelector('.apply-now'),
      bannerWrap    : document.querySelector('.banner-wrap'),
      footNav       : document.querySelector('.foot-nav'),
      choseApply    : document.querySelector('#choseApply'),
      choseBg       : document.querySelector('.chose-bg'),
      choseWrap     : document.querySelector('.chose-wrap')
    };
  };

  setElemMap();
  bindElemEvent();
  elemMap.trimWrap.querySelector('div').click();
  handleChangeRange.apply(elemMap.moneyRange);

  splitChannel();
  adjustBannerHeight();
  fetchBanner();

  /*******************************S统计****************************/
  //收集一些统计所需的基本信息
  function collectBasicInfo() {
    var temp = {};
    //应用名
    temp.app = 'jqy';
    //平台
    temp.platform = 3;
    //入口
    var channel = util.splitUrl(location.search).channel;
    temp.Entrance = channel ? channel : 'H5';
    //市场
    temp.market = 'H5';
    //手机号
    temp.phone = '';
    //用户ID
    temp.userId = '';
    //手机型号
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
      temp.phoneModel = 'iPhone';
    } else if (/(Android)/i.test(navigator.userAgent)) {
      temp.phoneModel = 'Android';
    } else {
      temp.phoneModel = 'Android';
    }
    //手机品牌
    temp.phoneBrand = 'unknown';
    //手机标识,IP
    temp.phoneUniqueId = 'unknown';

    localStorage.TJBasic = JSON.stringify(temp);
  }

  //基本统计信息不存在，新建并收集信息
  if (!localStorage.TJBasic) {
    collectBasicInfo();
  }
  //如果统计信息存在，则上传统计信息
  if (localStorage.TJArray && localStorage.TJArray != '[]') {
    util.uploadTJInfo();
  }
  //如果统计信息数组不存在，则创建
  if (!localStorage.TJArray) {
    localStorage.TJArray = JSON.stringify([]);
  }
  /*******************************E统计****************************/
}());